from flask import Flask, jsonify, render_template
from bs4 import BeautifulSoup
import requests
from apscheduler.schedulers.background import BackgroundScheduler
import config

app = Flask(__name__)
latest_ai_news = []
ai_service_updates = {}


@app.route('/debug')
def debug_info():
    return {
        'news_count': len(latest_ai_news),
        'service_update_count': {k: len(v['updates']) for k, v in ai_service_updates.items()}
    }


def fetch_ai_updates():
    global latest_ai_news, ai_service_updates
    try:
        # 抓取通用AI新闻
        response = requests.get(config.AI_NEWS_URL)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')
        articles = soup.select(config.NEWS_SELECTOR)
        
        latest_ai_news = []
        for art in articles[:5]:
            title_elem = art.find('h2')
            link_elem = art.find('a')
            summary_elem = art.find(class_='summary') if art.find(class_='summary') else None
            
            if title_elem and link_elem:
                latest_ai_news.append({
                    'title': title_elem.text.strip(),
                    'summary': summary_elem.text.strip() if summary_elem else '暂无摘要',
                    'link': link_elem['href'] if link_elem['href'].startswith('http') else config.AI_NEWS_URL + link_elem['href']
                })
        
        # 抓取各AI服务平台更新
        for service, info in config.AI_SERVICES.items():
            try:
                resp = requests.get(info['url'], timeout=10)
                resp.raise_for_status()
                sp = BeautifulSoup(resp.text, 'html.parser')
                
                # 提取关键信息
                elements = sp.select(info['selector'])
                content = [elem.get_text(strip=True) for elem in elements[:5]]
                
                ai_service_updates[service] = {
                    'name': service,
                    'updates': content,
                    'url': info['url'],
                    'base_url': info['base_url']
                }
            except Exception as e:
                app.logger.error(f"抓取 {service} 失败: {str(e)}")
        
        app.logger.info(f"成功更新AI资讯共 {len(latest_ai_news)} 条")
        app.logger.info(f"平台更新详情: { {k: len(v['updates']) for k, v in ai_service_updates.items()} }")
    except Exception as e:
        app.logger.error(f"抓取失败: {str(e)}", exc_info=True)


@app.route('/')
def index():
    return render_template('ai_features.html', 
                           config=config,
                           news=latest_ai_news,
                           updates=ai_service_updates)

@app.route('/api/ai-news')
def get_ai_news():
    return jsonify({'data': latest_ai_news})

# 初始化定时任务
sched = BackgroundScheduler()
sched.add_job(fetch_ai_updates, 'interval', minutes=config.UPDATE_INTERVAL)
sched.start()

if __name__ == '__main__':
    app.run(debug=True)